using System;
using MySql.Data.MySqlClient; // 改用MySQL客户端
using System.Windows;
using System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;
using System.Windows.Input;

using System.IO;

using System.Linq;
using System.Collections.Generic;
using System.Windows.Markup;
using System.Xml.Linq;


namespace MainUI
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            HotkeyManager.Initialize(this);
            Loaded += OnLoaded;
            Closed += OnClosed;
        }

        private void SetSavePicPosButton_Click(object sender, RoutedEventArgs e)
        {
            // 【选择文件存储文件夹】
            using (var folderBrowser = new FolderBrowserDialog())  // 创建系统文件夹选择对话框
            {
                // 设置对话框的提示文本
                folderBrowser.Description = "请选择用于存储文件的文件夹";

                // 用户点击“确定”或“取消”
                var result = folderBrowser.ShowDialog();  // 返回值为 DialogResult.OK（确定）或 Cancel（取消）

                // 点击了“确定”
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    // 将用户选择的文件夹路径赋值给界面上的文本框（SavePicBox）显示
                    SavePicBox.Text = folderBrowser.SelectedPath; 
                }
                else
                {
                    // 用户未选择文件夹
                    MessageBox.Show(
                        "未选择任何文件夹",  // 提示内容
                        "提示",              // 对话框标题
                        MessageBoxButton.OK, // 按钮类型
                        MessageBoxImage.Warning  // 图标
                    );
                }
            }  


            // 【初始化 MySQL 数据库表】
            const string connectionString = "Server=localhost;Port=3306;Database=screenpic;Uid=root;Pwd=hjj1019583787;";


            // 建表 SQL 语句
            const string createTableSql = @"
CREATE TABLE IF NOT EXISTS screenshots (  -- 表名：screenshots（截图表）
    id BIGINT PRIMARY KEY AUTO_INCREMENT,  -- 主键：BIGINT 类型（长整型），自增（自动生成唯一 ID）
    file_name VARCHAR(255) NOT NULL,       -- 文件名：VARCHAR(255)（可变长度字符串，最多 255 字符），非空
    file_path VARCHAR(512) NOT NULL,       -- 文件路径：VARCHAR(512)（长路径支持），非空
    file_format VARCHAR(20) NOT NULL,      -- 文件格式（如 PNG、JPG）：VARCHAR(20)，非空
    capture_width INT NOT NULL,            -- 截图宽度：INT（整型），非空
    capture_height INT NOT NULL,           -- 截图高度：INT（整型），非空
    capture_area VARCHAR(50),              -- 截图区域（如全屏、自定义区域）：VARCHAR(50)，允许空
    create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,  -- 创建时间：DATETIME（日期时间），非空，默认当前时间
    last_modify_time DATETIME,             -- 最后修改时间：DATETIME，允许空
    is_deleted TINYINT NOT NULL DEFAULT 0, -- 是否删除：TINYINT（小整型），非空，默认 0（未删除）
    parent_screenshot BIGINT,              -- 父截图 ID（用于关联截图版本）：BIGINT，允许空
    FOREIGN KEY (parent_screenshot) REFERENCES screenshots(id)  -- 外键约束：关联自身的 id 字段
) ENGINE=InnoDB;"; 

    // 数据库操作（连接、建表）
    try
            {
                using (var connection = new MySqlConnection(connectionString))  // 创建 MySQL 连接对象
                {
                    connection.Open();  // 打开数据库连接

                    using (var command = new MySqlCommand(createTableSql, connection))  // 创建 SQL 命令对象
                    {
                        command.ExecuteNonQuery();  // 执行
                    }
                }  
                // 建表成功
                MessageBox.Show(
                    "数据库连接成功，表结构初始化完成", 
                    "提示",                         
                    MessageBoxButton.OK,                
                    MessageBoxImage.Information          
                );
            }
            catch (Exception ex)  // 捕获数据库操作中的异常
            {
                // 异常提示
                MessageBox.Show(
                    $"数据库操作失败：{ex.Message}",  
                    "错误",                         
                    MessageBoxButton.OK,             
                    MessageBoxImage.Error            
                );
            }
        }

        private void ViewPicButton_Click(object sender, RoutedEventArgs e)
        {
            // 检查保存路径输入框是否为空或仅包含空白字符（空格、制表符等）
            if (string.IsNullOrWhiteSpace(SavePicBox.Text))
            {
                // 若路径无效，弹出错误提示框
                MessageBox.Show("请先选择图片存储路径", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 定义生成的HTML文件完整路径
            string htmlPath = System.IO.Path.Combine(SavePicBox.Text, "screenshot_viewer.html");

            try
            {
                // 用于存储从数据库读取的元数据（记录列表，每条记录是键值对字典）
                var metaData = new List<Dictionary<string, object>>();

                const string connectionString = "Server=localhost;Port=3306;Database=screenpic;Uid=root;Pwd=hjj1019583787;";

                using (var connection = new MySqlConnection(connectionString))
                {
                    // 打开数据库连接
                    connection.Open();

                    // 定义要执行的SQL查询语句
                    const string query = "SELECT id, file_name, file_path, file_format, create_time FROM screenshots";

                    using (var command = new MySqlCommand(query, connection))  // 创建数据库命令对象
                    using (var reader = command.ExecuteReader())               // 执行查询并获取数据读取器
                    {
                        // 循环读取每一条记录
                        while (reader.Read())
                        {
                            var record = new Dictionary<string, object>();
                            // 遍历当前记录的所有字段
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                record[reader.GetName(i)] = reader.GetValue(i);
                            }
                            // 将单条记录添加到元数据列表
                            metaData.Add(record);
                        }
                    }
                }

                //生成html
                var html = new System.Text.StringBuilder();
                html.AppendLine("<!DOCTYPE html>");
                html.AppendLine("<html lang=\"zh-CN\">");
                html.AppendLine("<head>");
                html.AppendLine("<meta charset=\"UTF-8\">");
                html.AppendLine("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
                html.AppendLine("<title>截图查看器</title>");
                html.AppendLine("<style>");
                html.AppendLine("body { font-family: 'Segoe UI', sans-serif; margin: 20px; background-color: #f5f7fa; }");
                html.AppendLine(".container { max-width: 1200px; margin: 0 auto; }");
                html.AppendLine(".header { display: flex; flex-direction: column; gap: 15px; align-items: flex-start; margin-bottom: 20px; }");
                html.AppendLine(".search-container { display: flex; gap: 15px; width: 100%; }");
                html.AppendLine(".search-label { display: flex; align-items: center; gap: 8px; flex: 1; }");
                html.AppendLine(".search-input { flex: 1; padding: 8px 12px; border: 1px solid #e2e8f0; border-radius: 6px; font-size: 0.9em; }");
                html.AppendLine(".sort-options { display: flex; gap: 15px; align-items: center; }");
                html.AppendLine(".sort-label { display: flex; align-items: center; gap: 5px; cursor: pointer; }");
                html.AppendLine(".delete-btn { padding: 6px 12px; background-color: #e53e3e; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 0.85em; transition: background-color 0.2s; }");
                html.AppendLine(".delete-btn:hover { background-color: #c53030; }");
                html.AppendLine(".image-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; }");
                html.AppendLine(".image-card { background: white; padding: 12px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); transition: transform 0.2s ease; position: relative; }");
                html.AppendLine(".image-card:hover { transform: translateY(-4px); }");
                html.AppendLine(".image-card .select-checkbox { position: absolute; top: 8px; left: 8px; z-index: 10; }");
                html.AppendLine(".image-preview { width: 100%; height: 200px; object-fit: cover; border-radius: 4px; }");
                html.AppendLine(".file-name { margin: 8px 0 0; color: #4a5568; font-size: 0.9em; text-align: center; overflow: hidden; text-overflow: ellipsis; }");
                html.AppendLine(".file-meta { font-size: 0.8em; color: #718096; text-align: center; margin-top: 4px; }");
                html.AppendLine(".hidden { display: none; }");
                html.AppendLine(".delete-modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 100; align-items: center; justify-content: center; }");
                html.AppendLine(".modal-content { background-color: white; padding: 20px; border-radius: 8px; width: 90%; max-width: 400px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); }");
                html.AppendLine(".modal-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 15px; }");
                html.AppendLine(".btn { padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; font-size: 0.9em; }");
                html.AppendLine(".btn-primary { background-color: #2b6cb0; color: white; }");
                html.AppendLine(".btn-danger { background-color: #e53e3e; color: white; }");
                html.AppendLine("</style>");
                html.AppendLine("</head>");
                html.AppendLine("<body>");
                html.AppendLine("<div class=\"container\">");
                html.AppendLine("<div class=\"header\">");
                html.AppendLine("<h1 style=\"color: #2d3748; margin: 0;\">截图列表</h1>");
                html.AppendLine("<div class=\"search-container\">");
                html.AppendLine("<label class=\"search-label\"><span style=\"color: #4a5568;\">文件名搜索：</span><input type=\"text\" id=\"searchFileName\" class=\"search-input\" placeholder=\"支持正则匹配（如.*截图.*）\"></label>");
                html.AppendLine("<label class=\"search-label\"><span style=\"color: #4a5568;\">时间搜索：</span><input type=\"text\" id=\"searchTime\" class=\"search-input\" placeholder=\"支持正则匹配（如^2025-05-23）\"></label>");
                html.AppendLine("</div>");
                html.AppendLine("<div class=\"sort-options\">");
                html.AppendLine("<label class=\"sort-label\"><input type=\"checkbox\" id=\"sortByName\"><span>按名称排序（升序）</span></label>");
                html.AppendLine("<label class=\"sort-label\"><input type=\"checkbox\" id=\"sortByTime\"><span>按时间排序（最近）</span></label>");
                html.AppendLine("<button id=\"deleteBtn\" class=\"delete-btn\">删除选中</button>");
                html.AppendLine("</div>");
                html.AppendLine("</div>");
                html.AppendLine("<div class=\"image-grid\" id=\"imageGrid\">");

                foreach (var item in metaData)
                {
                    string fileName = item["file_name"].ToString();
                    DateTime createTime = (DateTime)item["create_time"];
                    string filePath = System.IO.Path.Combine(SavePicBox.Text, fileName);
                    string displayTime = createTime.ToString("yyyy-MM-dd HH:mm:ss");

                    html.AppendLine($"<div class=\"image-card\" data-name=\"{System.Web.HttpUtility.HtmlEncode(fileName)}\" data-time=\"{displayTime}\" data-path=\"{System.Web.HttpUtility.HtmlEncode(filePath)}\">");
                    html.AppendLine($"<input type=\"checkbox\" class=\"select-checkbox\" data-file=\"{System.Web.HttpUtility.HtmlEncode(fileName)}\">");
                    if (System.IO.File.Exists(filePath))
                    {
                        html.AppendLine($"<img class=\"image-preview\" src=\"file:///{filePath.Replace(@"\", "/")}\" alt=\"{System.Web.HttpUtility.HtmlEncode(fileName)}\"/>");
                    }
                    else
                    {
                        html.AppendLine("<div class=\"image-preview\" style=\"background: #f0f4f8; display: flex; align-items: center; justify-content: center;\"><span style=\"color: #a0aec0;\">图片丢失</span></div>");
                    }
                    html.AppendLine($"<div class=\"file-name\">{System.Web.HttpUtility.HtmlEncode(fileName)}</div>");
                    html.AppendLine($"<div class=\"file-meta\">{displayTime} · {item["file_format"]}</div>");
                    html.AppendLine("</div>");
                }

                html.AppendLine("</div>");
                html.AppendLine("</div>");
                html.AppendLine("<div class=\"delete-modal\" id=\"deleteModal\">");
                html.AppendLine("<div class=\"modal-content\">");
                html.AppendLine("<h3 style=\"color: #2d3748; margin-top: 0;\">确认删除</h3>");
                html.AppendLine("<p>您确定要删除选中的 <span id=\"deleteCount\">0</span> 张图片吗？</p>");
                html.AppendLine("<div class=\"modal-actions\">");
                html.AppendLine("<button id=\"cancelDelete\" class=\"btn\">取消</button>");
                html.AppendLine("<button id=\"confirmDelete\" class=\"btn btn-danger\">删除</button>");
                html.AppendLine("</div>");
                html.AppendLine("</div>");
                html.AppendLine("</div>");
                html.AppendLine("<script>");
                html.AppendLine("const searchFileName=document.getElementById('searchFileName'),searchTime=document.getElementById('searchTime'),sortByName=document.getElementById('sortByName'),sortByTime=document.getElementById('sortByTime'),imageGrid=document.getElementById('imageGrid'),deleteBtn=document.getElementById('deleteBtn'),deleteModal=document.getElementById('deleteModal'),deleteCount=document.getElementById('deleteCount'),cancelDelete=document.getElementById('cancelDelete'),confirmDelete=document.getElementById('confirmDelete');");
                html.AppendLine("let selectedFiles=[];");
                html.AppendLine("function filterAndSortCards(){const cards=Array.from(imageGrid.children),nameRegex=searchFileName.value?new RegExp(searchFileName.value,'i'):null,timeRegex=searchTime.value?new RegExp(searchTime.value,'i'):null;const filteredCards=cards.filter(card=>{const nameMatch=!nameRegex||nameRegex.test(card.dataset.name),timeMatch=!timeRegex||timeRegex.test(card.dataset.time);return nameMatch&&timeMatch});filteredCards.sort((a,b)=>{if(sortByName.checked)return a.dataset.name.localeCompare(b.dataset.name);if(sortByTime.checked)return new Date(b.dataset.time)-new Date(a.dataset.time);return 0});cards.forEach(card=>card.classList.add('hidden'));filteredCards.forEach(card=>{card.classList.remove('hidden');imageGrid.appendChild(card)});updateDeleteButtonState()}");
                html.AppendLine("function updateDeleteButtonState(){const selected=document.querySelectorAll('.select-checkbox:checked');deleteBtn.disabled=selected.length===0;deleteBtn.style.opacity=selected.length===0?'0.5':'1'}");
                html.AppendLine("deleteBtn.addEventListener('click',()=>{const selectedCheckboxes=document.querySelectorAll('.select-checkbox:checked');if(selectedCheckboxes.length===0)return;selectedFiles=Array.from(selectedCheckboxes).map(checkbox=>{const card=checkbox.closest('.image-card');return{name:card.dataset.name,path:card.dataset.path}});deleteCount.textContent=selectedFiles.length;deleteModal.style.display='flex'});");
                html.AppendLine("cancelDelete.addEventListener('click',()=>{deleteModal.style.display='none';selectedFiles=[]});");
                html.AppendLine("confirmDelete.addEventListener('click',()=>{if(selectedFiles.length===0){deleteModal.style.display='none';return}selectedFiles.forEach(file=>{const card=document.querySelector(`.image-card[data-name=\"${ file.name}\"]`);card&&card.remove()});deleteModal.style.display='none';selectedFiles=[];updateDeleteButtonState()});");
                html.AppendLine("imageGrid.addEventListener('change',e=>{e.target.classList.contains('select-checkbox')&&updateDeleteButtonState()});");
                html.AppendLine("[searchFileName,searchTime].forEach(input=>input.addEventListener('input',()=>{sortByName.checked=!1;sortByTime.checked=!1;filterAndSortCards()}));");
                html.AppendLine("[sortByName,sortByTime].forEach(checkbox=>checkbox.addEventListener('change',e=>{if(e.target.checked){const otherCheckbox=e.target===sortByName?sortByTime:sortByName;otherCheckbox.checked=!1}filterAndSortCards()}));");
                html.AppendLine("</script>");
                html.AppendLine("</body>");
                html.AppendLine("</html>");

                System.IO.File.WriteAllText(htmlPath, html.ToString());

                MessageBox.Show(
                    $"查看文件已生成至：\n{htmlPath}",
                    "生成成功",
                    MessageBoxButton.OK,
                    MessageBoxImage.Information
                );

                System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{htmlPath}\"");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成查看页面失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }



        private int _fixedHotkeyId = -1;
        private int _customHotkeyId = -1;


        private void SetPRSCButton_Click(object sender, RoutedEventArgs e)
        {
            var settingsWindow = new HotkeySettingsWindow();
            if (settingsWindow.ShowDialog() == true)
            {
                RegisterHotkeys();
            }
        }
        private void RegisterHotkeys()
        {
            if (!string.IsNullOrEmpty(Properties.Settings.Default.FixedHotkey))
            {
                var (fixedMod, fixedKey) = ParseHotkey(Properties.Settings.Default.FixedHotkey);
                _fixedHotkeyId = HotkeyManager.Register(fixedMod, fixedKey, CaptureFixedScreenshot);
            }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.CustomHotkey))
            {
                var (customMod, customKey) = ParseHotkey(Properties.Settings.Default.CustomHotkey);
                _customHotkeyId = HotkeyManager.Register(customMod, customKey, CaptureCustomScreenshot);
            }
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
            {
                // 注册热键
                try
                {
                    var (fixedMod, fixedKey) = ParseHotkey(Properties.Settings.Default.FixedHotkey);
                    _fixedHotkeyId = HotkeyManager.Register(fixedMod, fixedKey, CaptureFixedScreenshot);

                    var (customMod, customKey) = ParseHotkey(Properties.Settings.Default.CustomHotkey);
                    _customHotkeyId = HotkeyManager.Register(customMod, customKey, CaptureCustomScreenshot);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "热键初始化失败", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            private void OnClosed(object sender, EventArgs e)
            {
                // 注销热键
                if (_fixedHotkeyId != -1) HotkeyManager.Unregister(_fixedHotkeyId);
                if (_customHotkeyId != -1) HotkeyManager.Unregister(_customHotkeyId);
            }

            private (ModifierKeys modifiers, Key key) ParseHotkey(string hotkey)
            {
                if (string.IsNullOrEmpty(hotkey)) throw new ArgumentException("空快捷键配置");

                var parts = hotkey.Split(new[] { "+" }, StringSplitOptions.RemoveEmptyEntries)
                                 .Select(p => p.Trim())
                                 .ToArray();

                ModifierKeys mods = ModifierKeys.None;
                Key finalKey = Key.None;

                foreach (var part in parts.Take(parts.Length - 1))
                {
                    switch (part.ToUpper())
                    {
                        case "CTRL": mods |= ModifierKeys.Control; break;
                        case "ALT": mods |= ModifierKeys.Alt; break;
                        case "SHIFT": mods |= ModifierKeys.Shift; break;
                        case "WIN": mods |= ModifierKeys.Windows; break;
                        default: throw new FormatException($"无效的修饰键: {part}");
                    }
                }

                if (!Enum.TryParse(parts.Last(), true, out finalKey))
                {
                    throw new FormatException($"无效的按键: {parts.Last()}");
                }

                return (mods, finalKey);
            }

            private void CaptureFixedScreenshot()
            {
                try
                {
                    var size = Properties.Settings.Default.AreaSize.Split(',')
                        .Select(int.Parse).ToArray();

                    if (size.Length != 2) throw new InvalidOperationException("无效的截图尺寸配置");

                    // 实现固定区域截图
                    var screen = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
                    using (var bitmap = new System.Drawing.Bitmap(size[0], size[1]))
                    using (var graphics = System.Drawing.Graphics.FromImage(bitmap))
                    {
                        graphics.CopyFromScreen(
                            screen.Width / 2 - size[0] / 2,
                            screen.Height / 2 - size[1] / 2,
                            0, 0,
                            new System.Drawing.Size(size[0], size[1])
                        );

                        SaveScreenshot(bitmap);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"固定截图失败: {ex.Message}", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            private void CaptureCustomScreenshot()
            {
                try
                {
                    // 实现拖拽区域截图
                    var regionSelector = new RegionSelectorWindow();
                    if (regionSelector.ShowDialog() == true)
                    {
                        var rect = regionSelector.SelectedRegion;
                        using (var bitmap = new System.Drawing.Bitmap((int)rect.Width, (int)rect.Height))
                        using (var graphics = System.Drawing.Graphics.FromImage(bitmap))
                        {
                            graphics.CopyFromScreen(
                                (int)rect.Left,
                                (int)rect.Top,
                                0, 0,
                                new System.Drawing.Size((int)rect.Width, (int)rect.Height)
                            );

                            SaveScreenshot(bitmap);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"区域截图失败: {ex.Message}", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

        private void SaveScreenshot(System.Drawing.Bitmap bitmap)
        {
            // 检查保存路径是否有效
            if (string.IsNullOrWhiteSpace(SavePicBox.Text))
            {
                MessageBox.Show("请先选择图片存储路径", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                // 生成文件名和完整路径
                string fileName = $"Screenshot_{DateTime.Now:yyyyMMddHHmmss}.png";
                string saveDir = SavePicBox.Text.Trim();
                string savePath = Path.Combine(saveDir, fileName);

                // 确保目录存在
                Directory.CreateDirectory(saveDir);

                // 保存图片文件
                bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);

                // 数据库连接信息
                const string connectionString = "Server=localhost;Port=3306;Database=screenpic;Uid=root;Pwd=hjj1019583787;";

                // 插入数据库记录
                using (var connection = new MySqlConnection(connectionString))
                {
                    connection.Open();

                    const string insertSql = @"
INSERT INTO screenshots 
    (file_name, file_path, file_format, capture_width, capture_height, create_time)
VALUES
    (@name, @path, @format, @width, @height, @createTime)";

                    using (var cmd = new MySqlCommand(insertSql, connection))
                    {
                        cmd.Parameters.AddWithValue("@name", fileName);
                        cmd.Parameters.AddWithValue("@path", savePath);
                        cmd.Parameters.AddWithValue("@format", "PNG");
                        cmd.Parameters.AddWithValue("@width", bitmap.Width);
                        cmd.Parameters.AddWithValue("@height", bitmap.Height);
                        cmd.Parameters.AddWithValue("@createTime", DateTime.Now);

                        int affectedRows = cmd.ExecuteNonQuery();

                        if (affectedRows > 0)
                        {
                            MessageBox.Show($"截图已保存至: {savePath}\n数据库记录已更新", "完成",
                                MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            MessageBox.Show("图片保存成功，但数据库写入失败", "警告",
                                MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

    }
}